package com.mszlu.news.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mszlu.news.dao.dos.Archives;
import com.mszlu.news.dao.mapper.*;
import com.mszlu.news.dao.pojo.*;
import com.mszlu.news.service.*;
import com.mszlu.news.utils.UserThreadLocal;
import com.mszlu.news.vo.ArticleBodyVo;
import com.mszlu.news.vo.ArticleVo;
import com.mszlu.news.vo.Result;
import com.mszlu.news.vo.TagVo;
import com.mszlu.news.vo.params.ArticleParam;
import com.mszlu.news.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private ComplainMapper complainMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticle(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records, true, true));
    }

    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.last("limit " + limit);
        //select id,title from article order by view_counts desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId, Article::getTitle);
        queryWrapper.last("limit " + limit);
        //select id,title from article order by create_date desc desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result hotArticleByCategory(Long categoryId) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.eq(Article::getCategoryId,categoryId);
        queryWrapper.last("limit " +5);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, true, true));
    }

    @Override
    public Result hotArticleByTag(Long tagId) {
        List<Article> articles = articleMapper.listhotArticleByTag(tagId);
        return Result.success(copyList(articles, true, true));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Autowired
    private ThreadService threadService;

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1. 根据id查询 文章信息
         * 2. 根据bodyId和categoryid 去做关联查询
         */
        Article article = this.articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true, true, true);
        threadService.updateArticleViewCount(articleMapper, article);
        return Result.success(articleVo);
    }

    @Override
    public Result findArticleByAuthorId(Long authorId) {
        List<Article> articleList = articleMapper.listArticle1(authorId);
        return Result.success(copyList(articleList, true, true));
    }

    @Override
    public Result selectArticle(ArticleParam articleParam) {
        List<Article> articleList = articleMapper.selectArticle(articleParam.getTitle(), articleParam.getSummary());
        return Result.success(copyList(articleList,true,true,true,true));
    }

    @Override
    public Result publish(ArticleParam articleParam) {
        //此接口 要加入到登录拦截当中
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1. 发布文章 目的 构建Article对象
         * 2. 作者id  当前的登录用户
         * 3. 标签  要将标签加入到 关联列表当中
         * 4. body 内容存储 article bodyId
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setCollectCounts(0);
        article.setGoodCounts(0);

        article.setPreimg(articleParam.getPreimg());
        //插入之后 会生成一个文章id
            articleMapper.insert(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    @Override
    public Result updateArticle(ArticleParam articleParam) {
        Article article = new Article();
        article.setAuthorId(articleParam.getAuthorId());
        article.setId(articleParam.getId());
        article.setWeight(Article.Article_Common);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setPreimg(articleParam.getPreimg());

        articleMapper.updateById(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            LambdaQueryWrapper<ArticleTag> tagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            tagLambdaQueryWrapper.eq(ArticleTag::getArticleId,articleParam.getId());
            articleTagMapper.delete(tagLambdaQueryWrapper);
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body
//        ArticleBody articleBody = new ArticleBody();
//        articleBody.setArticleId(articleParam.getId());
//        articleBody.setContent(articleParam.getBody().getContent());
//        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
//        articleBodyMapper.updateById(articleBody);
        UpdateWrapper<ArticleBody> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("article_id", articleParam.getId());
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.update(articleBody, updateWrapper);

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String, String> map = new HashMap<>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    @Override
    public Result deleteArticleById(Long articleId) {
        articleMapper.deleteById(articleId);
        Map<String,Object> map=new HashMap<>();
        map.put("article_id",articleId);
        commentMapper.deleteByMap(map);
        collectMapper.deleteByMap(map);
        goodMapper.deleteByMap(map);
        complainMapper.deleteByMap(map);
        articleBodyMapper.deleteByMap(map);
        articleTagMapper.deleteByMap(map);
        return Result.success("文章删除成功");
    }

    @Override
    public Result carousel(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.isNotNull(Article::getPreimg);
        queryWrapper.eq(Article::getWeight,2);
        queryWrapper.last("limit 0,"+limit);
        List<Article> articleList=articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articleList,true,true));
    }

    @Override
    public Result secondCarousel(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.isNotNull(Article::getPreimg);
        queryWrapper.eq(Article::getWeight,1);
        queryWrapper.last("limit 0,"+limit);
        List<Article> articleList=articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articleList,true,true));
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor, false, false));
        }
        return articleVoList;
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor, isBody, isCategory));
        }
        return articleVoList;
    }

    @Autowired
    private CategoryService categoryService;


    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article, articleVo);

        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有的接口 都需要标签 ，作者信息
        if (isTag) {
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthorId(String.valueOf(article.getAuthorId()));
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
            articleVo.setAvatar(sysUserService.findUserById(authorId).getAvatar());
            articleVo.setV(sysUserService.findUserById(authorId).getV());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyById(bodyId));
        }
        if (isCategory) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }

}
